package com.mind.customer.service;

import com.mind.cache.lock.annotation.DMLock;
import com.mind.common.utils.ExceptionUtil;
import com.mind.common.utils.StringUtils;
import com.mind.common.utils.spring.SpringUtils;
import com.mind.customer.domain.vo.TaskResult;
import com.mind.customer.exception.CallbackException;
import com.mind.customer.handler.Handler;
import com.mind.customer.mapper.AjTicketTaskMapper;
import com.mind.customer.utils.EnvUtils;
import com.mind.system.domain.AjTicketTask;
import com.mind.system.mapper.SysConfigMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Log4j2
public class CustomerService {
    @Resource
    private AjTicketTaskMapper ticketTaskMapper;

    @Resource
    private SysConfigMapper configMapper;

    private Handler handler;
    @Resource
    private EnvUtils envUtils;


    @PostConstruct
    public void lazySetHandler() {
        String appName = envUtils.getPlatform();
        handler = SpringUtils.getBean(appName + "TicketHandler");
    }

    @DMLock(key = "#task.ticketId")
    @Async
    public void customerTicket(AjTicketTask task) {
        // 更新状态
        AjTicketTask newTask = new AjTicketTask();
        newTask.setId(task.getId());
        newTask.setStatus(2);
        ticketTaskMapper.updateTicketTask(newTask);
        // 处理此单据
        try {

            TaskResult result = handler.handler(task);
            // 成功
            if (1 == result.getStatus()) {
                newTask.setStatus(3);
                newTask.setErrorInfo("");
                newTask.setCompleteTime(new Date());
            }
            // 失败
            else {
                newTask.setStatus(4);
                newTask.setErrorInfo(result.getError());
                newTask.setCompleteTime(new Date());
            }
            ticketTaskMapper.updateTicketTask(newTask);
        }
        // 回调异常
        catch (CallbackException e) {
            log.info("回调异常：", e);
            newTask.setStatus(3);
            newTask.setCallbackStatus(1);
            newTask.setErrorInfo(StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000));
            newTask.setCompleteTime(new Date());
            ticketTaskMapper.updateTicketTask(newTask);
        }
        // 异常
        catch (Exception e) {
            log.info("处理单据异常：", e);
            String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
            newTask.setStatus(4);
            newTask.setErrorInfo(errorMsg);
            newTask.setCompleteTime(new Date());
            ticketTaskMapper.updateTicketTask(newTask);
        }
    }
}
